package com.tourism.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tourism.dao.HotelOrderDao;
import com.tourism.dao.RoomDao;
import com.tourism.entity.HotelOrder;
import com.tourism.entity.HotelOrderQuery;
import com.tourism.entity.OrderPayInfo;
import com.tourism.entity.Room;
import com.tourism.exception.ExceptionEnum;
import com.tourism.exception.GlobalException;
import com.tourism.service.HotelOrderService;
import com.tourism.util.SystemHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description
 * @Author z
 * @Date 2021-05-01 9:16
 */
@Service
public class HotelOrderServiceImpl implements HotelOrderService {
    @Autowired
    private HotelOrderDao hotelOrderDao;
    @Autowired
    private RoomDao roomDao;

    @Override
    public boolean addHotelOrder(HotelOrder hotelOrder) throws GlobalException {
//        Room room = roomDao.getRoomById(hotelOrder.getRoomId());
//
//        //如果房间数量不够，则抛出对应异常
//        if (hotelOrder.getRoomNum() > room.getNum()) {
//            throw new GlobalException(ExceptionEnum.RoomNumNotEnough);
//        }
        hotelOrder.setOrderUser(SystemHelper.getUserId());
        hotelOrder.init();
        hotelOrderDao.addHotelOrder(hotelOrder);
        //酒店订单生成之后，需要修改房间数量
        roomDao.updateRoomNum(hotelOrder.getRoomId(), -1 * hotelOrder.getRoomNum());
        return true;
    }

    @Override
    public boolean deleteHotelOrder(Long id) throws GlobalException {
        HotelOrder hotelOrder = hotelOrderDao.getHotelOrderById(id);
        if (hotelOrder.isPay()) {
            throw new GlobalException(ExceptionEnum.OrderAlreadyPay);
        }
        //删除订单的时候，需要将房间的数量增加
        roomDao.updateRoomNum(hotelOrder.getRoomId(), hotelOrder.getRoomNum());
        hotelOrderDao.deleteHotelOrderById(id);
        return true;
    }

    @Override
    public HotelOrder getHotelOrderById(Long id) {
        return hotelOrderDao.getHotelOrderById(id);
    }

    @Override
    public PageInfo<HotelOrder> getHotelOrderList(HotelOrderQuery query) {
//        部分参数作为分页的参数
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        //判断是否是管理员（管理员查询所有，否之用户只能查询自己的）
        if (!SystemHelper.isAdmin()) {
            query.setOrderUser(SystemHelper.getUserId());
        }
        List<HotelOrder> CustomLineList = hotelOrderDao.getHotelOrderList(query);
        PageInfo<HotelOrder> result = new PageInfo<>(CustomLineList);
        return result;
    }

    @Override
    public boolean updateOrderPayInfo(OrderPayInfo orderPayInfo) {
        orderPayInfo.init();
        return hotelOrderDao.updateOrderPayInfo(orderPayInfo);
    }

}
